package com.nzy.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nzy.common.CacheKey;
import com.nzy.common.RedisUtil;
import com.nzy.entity.Stock;
import com.nzy.entity.StockMq;
import com.nzy.entity.StockRecord;
import com.nzy.service.StockRecordService;
import com.nzy.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
@EnableBinding(OrderSink.class)
@Slf4j
public class MessageConsumer {

    @Autowired
    private StockService stockService;

    @Autowired
    private StockRecordService stockRecordService;
    @Autowired
    private RedisUtil redisUtil;


    @StreamListener(OrderSink.DEFAULT)
    public void receive(Message<Map<String, Object>> message){
        String text = JSON.toJSONString(message);
        Map<String, Object> params = message.getPayload();
        Integer orderId = (Integer) params.get("orderId");
        String skuId = (String) params.get("skuId");
        String userId = (String) params.get("userId");
        Integer number = (Integer) params.get("number");
        if(stockRecordService.getStockMq(orderId) > 0){
            log.error(" MessageConsumer 消息重复，扣库存失败：" + text);
            return;
        }
        Stock stock = stockService.queryBySkuId(skuId);
        if(stock == null) {
            log.error(" MessageConsumer 商品不存在，扣库存失败：" + text);
            return;
        }
        String key = CacheKey.getStockNumBySkuId(skuId);
         Integer stockNum = (Integer) redisUtil.get(key);
        if(stockNum == null || stockNum < number){
            log.error(" MessageConsumer 商品库存不足，扣库存失败：" + text);
            return;
        }
        Date date = new Date();
        stock.setStock(number);
        stock.setUpdateTime(date);
        stockService.subStock(stock);

        StockMq mq = new StockMq();
        mq.setMsgId((String) params.get("msgId"));
        mq.setNumber(number);
        mq.setOrderId(orderId);
        mq.setSkuId(skuId);
        mq.setUserId(userId);
        mq.setCreateTime(date);
        stockRecordService.insertStockMq(mq);
        log.info(" MessageConsumer 扣库存成功：" + text);
    }
}
